import type { UserInfo } from "@/api/user";
import { defineStore } from "pinia";
import { ref } from "vue";
import * as AuthAPI from "@/api/user";
import { clearToken, setRefreshToken, setToken } from "@/utils/auth";
import { localUtils } from "@/utils/local";

export const useUserStore = defineStore("user", () => {
  const userInfo = ref<UserInfo | undefined>(localUtils.get<UserInfo>("userInfo"));

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: AuthAPI.LoginData) {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.login(loginData)
        .then((data) => {
          const { tokenType, accessToken, refreshToken } = data;
          setToken(tokenType + " " + accessToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          setRefreshToken(refreshToken);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
  /**
   * 获取用户信息
   *
   * @returns {UserInfo} 用户信息
   */
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      AuthAPI.getInfo()
        .then((data) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          userInfo.value = data;
          localUtils.set("userInfo", data);
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 登出
   */
  function logout() {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.logout()
        .then(() => {
          userInfo.value = undefined;
          clearUserData();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
  /**
   * 清理用户数据
   *
   * @returns
   */
  function clearUserData() {
    return new Promise<void>((resolve) => {
      clearToken();
      localUtils.clear();
      resolve();
    });
  }

  /**
   * 更新用户头像
   *
   * @param {string} avatarUrl - 新的头像URL
   */
  function updateAvatar(avatarUrl: string) {
    if (userInfo.value) {
      userInfo.value.avatar = avatarUrl;
      localUtils.set("userInfo", userInfo.value);
    }
  }

  return {
    userInfo,
    login,
    getUserInfo,
    logout,
    clearUserData,
    updateAvatar,
  };
});
